#include <sstream>
#include <map>
#include <vector>
#include <string>
#include <tuple>
#include <algorithm>
#include <boost/algorithm/string/replace.hpp>
#include "commandexecutor.h"
exec::exec(wingbox* box)
	: design(box)
{

	no_oper = [] (wingbox&, const arglist& a) { return ;};
}

exec::functionmap_const_iter exec::getFunction(const std::string& name) const
{
	return this->allfunctions.find(name);
}

bool exec::perform(const std::string& input) const
{
	std::stringstream ss(input);
	std::string funcname;
	ss >> funcname;
	if (funcname == "exit") { 
		return false;
	}
	if (funcname == "help") {
		displayHelp();
		return true;

	}
	ss.get();

	auto i(getFunction(funcname));
	if (i != allfunctions.end()) {
		const functor& foo(std::get<0>(i->second));
		std::string t;
		arglist args;
		while (std::getline(ss, t, ',')) {
			args.push_back(t);
		}
		foo(*design, args);
	}
	return true;
}
void exec::RegisterFunc(const std::string& name, const functor& function, const std::string& help)
{
	allfunctions[name] = std::make_tuple(function, help);
}

void exec::displayHelp() const
{
	std::for_each(allfunctions.begin(), allfunctions.end(), [] (const decltype(*allfunctions.begin())& i) {
		std::string prefix(i.first.length() + 2, ' ');
		std::string help(std::get<1>(i.second));
		
		boost::replace_all(help, "\n", std::string("\n") + prefix);
		std::cout << i.first << ": " << help << std::endl;
	});
}